<template>
  <div class="app-container">
    <div class="title-btns">
      <span class="role-span"><span></span>角色权限配置</span>
    </div>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17">
        <el-card class="box-card">
          <div class="head-container">
            <!-- 搜索 -->
            <el-input v-model="query.value" clearable placeholder="输入名称搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />
            <el-select v-model="query.status" clearable placeholder="状态" class="filter-item" style="width: 90px" @change="toQuery">
              <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
            </el-select>
            <el-button class="filter-item" size="mini" type="primary" icon="el-icon-search" @click="toQuery">搜索</el-button>
            <el-button class="filter-item" size="mini" icon="el-icon-refresh" @click="toReSet">重置</el-button>
            <el-button
              v-permission="['ADMIN','ROLES_ALL','ROLES_CREATE']"
              class="filter-item"
              size="mini"
              type="primary"
              icon="el-icon-plus"
              @click="toAdd"
            >新增</el-button>
            <!-- 新增 -->
            <div id="opt" style="float: right">

              <el-radio-group v-model="opt" size="mini">
                <el-radio-button label="菜单分配" />
                <el-radio-button label="权限分配" />
              </el-radio-group>
            </div>

          </div>
          <el-table v-loading="loading" :data="data" highlight-current-row size="small" style="width: 100%;" @current-change="handleCurrentChange">
            <el-table-column prop="name" label="名称" align="center" />
            <el-table-column prop="code" label="代码" align="center" />
            <el-table-column prop="dataScope" label="数据权限" align="center" />
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <div v-for="item in dicts" :key="item.id">
                  <template v-if="scope.row.status.toString() === item.value" :type="scope.row.status ? '' : 'info'">{{ item.label }}</template>
                </div>
              </template>
            </el-table-column>
            <!--<el-table-column prop="level" label="角色级别"/>-->
            <el-table-column :show-overflow-tooltip="true" prop="createDate" label="创建日期" align="center">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createDate) }}</span>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="remark" label="描述" align="center" />
            <el-table-column v-if="checkPermission(['ADMIN','ROLES_ALL','ROLES_EDIT','ROLES_DELETE'])" label="操作" width="150px" align="center">
              <template slot-scope="scope">
                <el-button v-permission="['ADMIN','ROLES_ALL','ROLES_EDIT']" size="mini" type="text" @click="toUpdate(scope.row)">修改</el-button>
                <el-popover
                  :ref="scope.row.id"
                  v-permission="['ADMIN','ROLES_ALL','ROLES_DELETE']"
                  placement="top"
                  width="180"
                >
                  <p>此操作将删除角色与对应的权限与用户的关联数据，确定要删除吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                    <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
                  </div>
                  <el-button slot="reference" style="margin-left:10px" type="text" size="mini">删除</el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            :total="total"
            :current-page="page"
            style="margin-top: 8px;margin-bottom: 10px;"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="sizeChange"
            @current-change="pageChange"
          />
        </el-card>
      </el-col>
      <!-- 授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card v-show="opt === '菜单分配'" class="box-card">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              v-permission="['ADMIN','ROLES_ALL','ROLES_EDIT']"
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            accordion
            show-checkbox
            node-key="id"
          />
        </el-card>
        <el-card v-show="opt === '权限分配'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配权限" placement="top">
              <span class="role-span">权限分配</span>
            </el-tooltip>
            <el-button
              v-permission="['ADMIN','ROLES_ALL','ROLES_EDIT']"
              :disabled="!showButton"
              :loading="permissionLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="savePermission"
            >保存</el-button>
          </div>
          <el-tree
            ref="permission"
            :data="permissions"
            :default-checked-keys="permissionIds"
            :props="defaultProps"
            show-checkbox
            accordion
            node-key="id"
          />
        </el-card>
      </el-col>
    </el-row>
    <eForm ref="form" :dicts="dicts" :is-add="isAdd" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import { getPermissionTree } from '@/api/system/permission'
import { getMenusTree } from '@/api/system/menu'
import { parseTime } from '@/utils/index'
import eForm from './module/form'
import { editPermission, editMenu, get, del } from '@/api/system/role'
import initDict from '@/mixins/initDict'
export default {
  components: { eForm },
  mixins: [initData, initDict],
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentId: 0, permissionLoading: false, menuLoading: false, showButton: false, opt: '菜单分配',
      delLoading: false, sup_this: this, permissions: [], permissionIds: [], menus: [], menuIds: [],
      enabledTypeOptions: [
        { key: '0', display_name: '正常' },
        { key: '1', display_name: '禁用' }
      ]
    }
  },
  created() {
    this.getPermissions()
    this.getMenus()

    this.$nextTick(() => {
      this.init()
      this.getDict('status')
    })
  },
  methods: {
    parseTime,
    checkPermission,
    beforeInit() {
      this.$refs.permission.setCheckedKeys([])
      this.$refs.menu.setCheckedKeys([])
      this.showButton = false
      this.url = 'system/roles'
      const sort = 'DESC'
      const sortColumn = 'id'
      const query = this.query
      const value = query.value
      const status = query.status
      this.params = { page: this.page, size: this.size, sortColumn: sortColumn, sort: sort }
      if (value) { this.params['name'] = value }
      if (status) { this.params['status'] = status }
      return true
    },

    /**
    * 去新增
    */
    toAdd() {
      this.isAdd = true
      this.$refs.form.resetForm()
      this.$refs.form.dialog = true
    },

    /**
     * 去修改数据
     */
    toUpdate(data) {
      this.isAdd = false
      const _this = this.$refs.form
      _this.deptIds = []
      _this.form = { id: data.id, name: data.name, remark: data.remark, depts: data.depts, dataScope: data.dataScope, level: data.level, status: data.status.toString(), code: data.code }
      if (_this.form.dataScope === '自定义') {
        _this.getDepts()
      }
      get(data.id).then(res => {
        var pers = res.data.depts
        console.info(pers)
        pers.forEach(function(data, index) {
          _this.deptIds.push(data.id)
        })
      })
      _this.dialog = true
    },
    // 删除
    subDelete(id) {
      this.delLoading = true
      del(id).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.dleChangePage()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
        console.log(err.response.data.message)
      })
    },
    // 获取权限数据
    getPermissions() {
      getPermissionTree().then(res => {
        // console.info(res)
        this.permissions = res.data.tree
      })
    },
    // 获取菜单数据
    getMenus() {
      getMenusTree().then(res => {
        this.menus = res.data.list
      })
    },
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空权限与菜单的选中
        this.$refs.permission.setCheckedKeys([])
        this.$refs.menu.setCheckedKeys([])
        // 保存当前的角色id
        this.currentId = val.id
        // 点击后显示按钮
        this.showButton = true
        this.menuIds = []
        this.permissionIds = []
        // 初始化
        get(val.id).then((res) => {
          val.menus = res.data.menus
          val.permissions = res.data.permissions
          val.depts = res.data.depts
          // 菜单数据需要特殊处理
          val.menus.forEach(function(data, index) {
            let add = true
            for (let i = 0; i < val.menus.length; i++) {
              if (data.id === val.menus[i].pid) {
                add = false
                break
              }
            }
            if (add) {
              _this.menuIds.push(parseInt(data.id))
            }
          })
          // 处理权限数据
          val.permissions.forEach(function(data, index) {
            _this.permissionIds.push(parseInt(data.id))
          })

          this.$refs.permission.setCheckedKeys(_this.permissionIds)
          this.$refs.menu.setCheckedKeys(_this.menuIds)
        })
      }
    },
    // 保存权限数据
    savePermission() {
      this.permissionLoading = true
      const role = { id: this.currentId, sysPermissions: [] }
      this.$refs.permission.getCheckedKeys().forEach(function(data, index) {
        const permission = { id: data }
        role.sysPermissions.push(permission)
      })
      editPermission(role).then(res => {
        this.$notify({
          title: '保存成功',
          type: 'success',
          duration: 2500
        })
        this.permissionLoading = false
        this.update()
      }).catch(err => {
        this.permissionLoading = false
        console.log(err.response.data.message)
      })
    },
    // 保存已勾选的菜单
    saveMenu() {
      this.menuLoading = true
      const role = { id: this.currentId, menus: [] }
      // 得到半选的父节点数据，保存起来
      this.$refs.menu.getHalfCheckedNodes().forEach(function(data, index) {
        const permission = { id: data.id }
        role.menus.push(permission)
      })
      // 得到已选中的 key 值
      this.$refs.menu.getCheckedKeys().forEach(function(data, index) {
        const permission = { id: data }
        role.menus.push(permission)
      })

      editMenu(role).then(res => {
        this.$notify({
          title: '保存成功',
          type: 'success',
          duration: 2500
        })
        this.menuLoading = false
        this.update()
      }).catch(err => {
        this.menuLoading = false
        console.log(err.response.data.message)
      })
    },
    // 无刷新更新 表格数据
    update() {
      get(this.currentId).then(res => {
        for (let i = 0; i < this.data.length; i++) {
          if (res.id === this.data[i].id) {
            this.data[i] = res.data.role
            break
          }
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

</style>
